package com.lagou.edu.filter;

import com.lagou.edu.util.IpFlushFirewall;
import com.lagou.edu.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 赵虎
 * @date 2021/2/23 1:04 上午
 */
@Component
public class IpRequestFilter extends ResponseUtil implements GlobalFilter, Ordered {

    @Value("${config.request.iplimit.apis}")
    private String[] apis;

    @Value("${config.response.message.seeother}")
    private String seeOtherStatusText;

    @Autowired
    private IpFlushFirewall ipFlushFirewall;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        for (String restrictApi : apis) {
            if (antPathMatcher.match(restrictApi, path)) {
                return doFilter(exchange, chain);
            }
        }
        return chain.filter(exchange);
    }

    private Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String clientIp = IpFlushFirewall.getRequestClientIP(exchange.getRequest());

        boolean ipLimited = ipFlushFirewall.isIpLimited(clientIp);
        if (ipLimited) {
            return responseStatusAndMessage(exchange.getResponse(), HttpStatus.SEE_OTHER, seeOtherStatusText);
        }
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
